package com.example.crypt;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;


/**
 * RSA加密解密类,负责byte数组的加解密
 *
 * @author wzq
 * @2014年5月4日
 */
class TypeRsa implements IByteCrypt {
    private static final String TAG = "DesEncrypt";

    private Cipher encryptCipher = null;
    private Cipher decryptChiper = null;

    public TypeRsa() {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(1024);
            KeyPair kp = kpg.genKeyPair();
            Key publicKey = kp.getPublic();
            Key privateKey = kp.getPrivate();
            encryptCipher = Cipher.getInstance("RSA");
            encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
            decryptChiper = Cipher.getInstance("RSA");
            decryptChiper.init(Cipher.DECRYPT_MODE, privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** Encode the original data with RSA private key */
    @Override
    public byte[] encryptBytes(byte[] src) {
        try {
            return encryptCipher.doFinal(src);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** Decode the encoded data with RSA public key */
    @Override
    public byte[] decryptBytes(byte[] src) {
        try {
            return decryptChiper.doFinal(src);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
